<template>
  <!-- dbclick是vue内部封装好的一个方法，只有鼠标双击的时候才会触发 -->
  <div class="my-tag" @dblclick="editFn">
    <input
      class="input"
      type="text"
      placeholder="输入标签"
      v-if="edit"
      v-focus
      @blur="loseFocus"
      @keydown.enter="loseFocus"
      v-model="tag"
    />
    <!-- v-focus:自定义指令，当双击时会在页面上插入input，然后会触发inserted
      blur失去焦点时触发loseFocus -->
    <div class="text" v-else>{{ value }}</div>
  </div>
</template>

<script>
export default {
  // 接收传过来的值
  props: ['value'],
  data() {
    return {
      edit: false,
      tag: '',
    }
  },
  methods: {
    editFn() {
      this.edit = true
      this.tag = this.value
      // 将初始tag赋值为传过来的value
    },

    loseFocus() {
      this.edit = false
      // 当失去焦点或者按下回车时,将this.tag传给父组件
      this.$emit('input', this.tag)
    },
  },

  // 自定义指令,当绑定此指令的标签被插入页面时触发,触发聚焦事件
  directives: {
    focus: {
      inserted(e) {
        e.focus()
      },
    },
  },
}
</script>

<style lang="less" scoped>
.my-tag {
  cursor: pointer;
  .input {
    appearance: none;
    outline: none;
    border: 1px solid #ccc;
    width: 100px;
    height: 40px;
    box-sizing: border-box;
    padding: 10px;
    color: #666;
    &::placeholder {
      color: #666;
    }
  }
}
</style>
